package cn.zniot.so.apiprovide.business;

import cn.zniot.so.application.data.User;
import cn.zniot.so.database.DBManager;

import java.sql.SQLException;
import java.util.Map;


public class UserRegisterHandler extends AbstractHandler
{
	private static final String NAME = "name";
	private static final String PASS = "pass";
	private static final String BOX_ID = "box_id";
	private static final String EMAIL = "email";
	
	private Response response = null;
	private ErrorResponse errorResponse;
	
	public UserRegisterHandler() throws SQLException
	{
		super();
	}

	/**
	 * 方法名：handle(Map<String, String> params)
	 * 功　能：根据传入的参数查询数据库返回相应的obd信息
	 * 参　数：Map<String, String> params    -  &参数键值对
	 * 返回值：String - &xml文件包含头文件和实体内容
	 */
	public String handle(Map<String, String> paramMap) {
		String name = paramMap.get(NAME);
		String pass = paramMap.get(PASS);
		String box_id = paramMap.get(BOX_ID);
		String email = paramMap.get(EMAIL);
		
		// TODO 验证参数格式
		try
		{
			String box_id_exsit = DBManager.getInstance().isExistUsername(name);
			if (box_id_exsit!=null) {
			    response = new RegisterUserResponse(box_id_exsit);
			    String xmlStr = pageMaker(response.toJsonPage());
		        return xmlStr;
            }
			User user=new User();
			user.setName(name);
			user.setPass(pass);
			user.setEmail(email);
			user.setBox_id(box_id);
			String registService = DBManager.getInstance().registService(user);
			response = new RegisterUserResponse(registService);
		} catch (Exception e)
		{
			errorResponse=new ErrorResponse(e);
			String xmlStr = pageMaker(errorResponse.toJsonPage());
	        return xmlStr;
		}
		String xmlStr = pageMaker(response.toJsonPage());
		return xmlStr;
	}
	
}
